package com.yinlixian.frame.authentication.filter;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.regexp.internal.RE;
import com.yinlixian.frame.entity.ResultInfo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description:
 * @author: yudm
 * @date: 2017-04-25 20:43
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(CustomFormAuthenticationFilter.class);


    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        ResultInfo<Object> result = new ResultInfo<>();
        result.setResult(ResultInfo.Result.OK);
        printMessage(response,result);
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        log.debug("登录失败");
        ResultInfo<Object> result = new ResultInfo<>();
        result.setResult(ResultInfo.Result.LoginError);
        result.setMessage("账号或密码错误");
        printMessage(response,result);
        return false;
    }

    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = (HttpServletRequest)request;
        log.debug("请求地址："+req.getRequestURI());
        return super.onPreHandle(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        log.debug("访问未授权");
        if (isLoginRequest(request, response)) {
            log.debug("执行登录操作");
            return executeLogin(request, response);
        } else {
            ResultInfo<Object> result = new ResultInfo<>();
            result.setResult(ResultInfo.Result.AccessDenied);
            printMessage(response,result);
            return false;
        }
    }


    private void printMessage(ServletResponse response,Object message){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            String jo = JSONObject.toJSONString(message);
            out = response.getWriter();
            out.append(jo);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
